Example: Handling Errors with @@ERROR Function
In
this example, we will develop a stored procedure that inserts a new
credit card in the AdventureWorks2008 database and handle its output
with an @@ERRORFigure 1 shows the structure of the CreditCard table. function and some user-defined error messages.
To
standardize your database messages and make management efficient, you
decide to create two user-defined messages: one for the successful
insertion of a credit card and the other for an error that arises in
case of failure. Figure 2 shows the syntax of these messages.
You
can see that the severity level of these messages follows the SQL
Server standard for system messages, providing organization for them.
After you add the messages, the next step is the creation of your new
procedure. Based on the CreditCard table structure, you can create a procedure that receives four input parameters. Figure 3 shows the syntax of a new uspInsertValidatedCreditCard procedure.
Let’s
look at this code in detail. After you define the header part of the
procedure, you start the routine of the procedure declaring a local
variable called @Error. This local variable will store the @@ERROR value. Then, after the INSERT statement, you retrieve the @@ERROR value and set it as the @Error value. With the variable value defined, you can now analyze it using an IF
statement. If the value of the variable is 0, then there is no error
and the success message will be raised. Otherwise, an error will arise
and your custom error message will be shown.
Figure 4 shows the uspInsertValidatedCreditCard procedure being called twice and the last three CreditCard
table rows. The first call will return the successful message, while
the second will raise an error caused by a duplicate key violation in
the credit card number column.